package com.sensetime.bi.senselink.server.handler;

import com.sensetime.bi.senselink.server.entity.MediaSource;
import com.sensetime.bi.senselink.server.entity.rtp.TcpRtpPacket;
import com.sensetime.bi.senselink.server.rtsp.session.Session;
import com.sensetime.bi.senselink.server.rtsp.session.SessionManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;

import static com.sensetime.bi.senselink.server.constant.Constant.SESSION_ID;

@Slf4j
public class ForwardRTPToMediaHandler extends SimpleChannelInboundHandler<TcpRtpPacket> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, TcpRtpPacket msg) throws Exception {
        Channel channel = ctx.channel();
        log.debug("received rtp msg from " + channel.remoteAddress() + ", msg:\n" );

        // Forward sent to Player server
        Attribute<String> sessionAttr = channel.attr(SESSION_ID);
        if (sessionAttr == null) {
            log.error("client:" + channel.remoteAddress() + ", process response error: cannot found session info!");
            return;
        }
        String sessionId = sessionAttr.get();
        Session session = SessionManager.getSession(sessionId);
        MediaSource mediaSource = session.getMediaSource();
        // 发送
        mediaSource.sendRespnse(msg);
    }


}
